import React, { useEffect, useState } from 'react';
import { Form, Button, Typography, Flex, Input, message, Col, Select } from 'antd';
import { useTranslation } from 'react-i18next';
import RequestFormProjectTpl from '../../Components/RequestFormProjectTpl';
import RequestFormProductTpl from '../../Components/RequestFormProductTpl';
import { useLocation, useNavigate } from 'react-router-dom';
import { apiSysTemplateInitiate } from '../../../services/common';
import { apiSearchRequestAdd, apiSearchRequestView, apiSearchRequestEdit, apiSearchSpaUpload } from '../../../services/search/request';
import { ACCEPT_TYPE, REQUEST_PAGE, APPROVAL_STATUS, RES_MODE } from '../../../utils/constant';
import { getUserName, resquestDetialAttachmentFormat, transformArray, formatRequestItemData } from '../../../utils/commonUtil';
import _, { forEach } from 'lodash';
import RequestApprovalBtn from '../../Components/RequestApprovalBtn';
import UploadImg from '../Components/UploadImg';
import UploadFile from '../Components/UploadFile';
import './index.scss'
import { apiMSDTagSelect, apiMSDTagBatchAdd } from '../../../services/masterData/tag';
import ChooseImageModal from '../Components/ChooseImageModal'

const { Title } = Typography;
const SynTouchRequestDetails = () => {
  const { APPROVED, REJECTED, PENDING, DRAFT } = APPROVAL_STATUS;
  const { t } = useTranslation();
  const navigate = useNavigate();
  const [form] = Form.useForm();
  const location = useLocation();
  if (!location?.state) {
    navigate('/search/list');
  };
  const queryParams = location?.state || {};
  console.log("🚀 ~ SynTouchRequestDetails ~ queryParams:", queryParams)
  const { tplId, tBu, searchRequestId, editMode, approveRequestSituationId, tMd, tTm } = queryParams;
  const [initialValues, setInitialValues] = useState();
  const [requestStatus, setRequestStatus] = useState()
  const [compTagList, setCompTagList] = useState([]);
  //
  const [chooseImageModalVisable, setChooseImageModalVisable] = useState(false)
  const [linkImage, setLinkImage] = useState()

  // mock permission
  const isCampAdmin = true;
  const isBuPRPD = false;
  const isBuAdmin = false;
  const isBuTester = false;

  const isSEM = initialValues?.project?.moduleName?.fieldValue === 'SEM';


  const methodList = [{
    value: t('search.method'),
    label: t('search.method'),
  }];

  const apiMSDTagSelectAsync = (productListName) => {
    const params = {
      buType: productListName.buType.fieldValue,
      moduleName: productListName.moduleName.fieldValue
    }
    apiMSDTagSelect(params).then((res) => {
      if (res?.data) {
        setCompTagList(transformArray(res.data.data.item));
      }
    })
  }

  const apiSynTouchRequestSaveAsync = async (type) => {
    const formData = form?.getFieldsValue();
    const prjData = {
      product: formData?.product,
      project: formData?.project,
      userId: getUserName(),
      operationType: type,
      moduleName: formData?.project?.moduleName?.fieldValue,
      requestStatus
    };
    const data = editMode === RES_MODE.NEW ? await apiSearchRequestAdd(prjData) : await apiSearchRequestEdit({ ...prjData, searchRequestId });
    // console.log(data);
    if (data?.data?.code === 200) {
      apiMSDTagBatchAddAsync()
      message.success(t('common.saveSuccess'));
      navigate('/search/list')
    }
  };
  const saveClickHandle = (type) => {
    console.log(form.getFieldsValue());
    form.validateFields().then(() => {
      apiSynTouchRequestSaveAsync(type);
    }, () => {
      return false;
    });
  };

  const apiMSDTagBatchAddAsync = () => {
    const projectList = form?.getFieldsValue()?.project;
    const productList = form?.getFieldsValue()?.product;
    const filteredSet = new Set()
    productList?.forEach(item => {
      item?.attachmentUrl?.fieldValue?.forEach(value => {
        const filterVal = value?.tagValue?.filter(d => !compTagList.some(tag => tag.value === d))
        if (filterVal && filterVal.length > 0) {
          filteredSet.add(filterVal[0])
        }
      })
    })
    const filteredArray = [...filteredSet]
    if (filteredArray.length > 0) {
      const params = {
        buType: projectList?.buType?.fieldValue,
        moduleName: projectList?.moduleName?.fieldValue,
        tags: filteredArray,
        userId: getUserName()
      }
      apiMSDTagBatchAdd(params).then((res) => {
        // if (res?.data) {
        //   message.success(t('common.tagSuccess'));
        // }
      })
    }

  }


  const getFileName = (name) => {
    if (!name) {
      return {}
    }
    const parts = name.toLowerCase().split('.');
    // 获取文件扩展名
    const extension = parts[parts.length - 1];
    const fileName = parts[0];
    return {
      extension,
      fileName
    }
  }

  const uploadSpaApi = async (formData) => {
    console.log("🚀 ~ uploadSpaApi ~ formData:", formData)
    const res = await apiSearchSpaUpload(formData)
    if (res?.data?.code === 200) {
      return res.data.data.items
    }
    // console.log("🚀 ~ uploadSpaApi ~ res:", res)
    // return [
    //   [{
    //     "attachmentInfoId": "5ff6d489-bc27-4ac8-9949-dcdcba27c683",
    //     "attachmentName": "img_3.spa",
    //     "attachmentUrl": "spaConversion/spa/img_3.spa"
    //   },
    //   {
    //     "attachmentInfoId": "f5916cf6-6bcd-46b1-ab2a-2762bac1f9c4",
    //     "attachmentName": "img_3.csv",
    //     "attachmentUrl": "spaConversion/csv/img_3.csv"
    //   },
    //   {
    //     "attachmentInfoId": "bb77fbb3-e83d-43a1-843e-ac50cc2d3b1b",
    //     "attachmentName": "img_3.png",
    //     "attachmentUrl": "spaConversion/image/img_3.png"
    //   }], [{
    //     "attachmentInfoId": "5ff6d489-bc27-4ac8-9949-dcdcba27c683",
    //     "attachmentName": "img_3.spa",
    //     "attachmentUrl": "spaConversion/spa/img_3.spa"
    //   },
    //   {
    //     "attachmentInfoId": "f5916cf6-6bcd-46b1-ab2a-2762bac1f9c4",
    //     "attachmentName": "img_3.csv",
    //     "attachmentUrl": "spaConversion/csv/img_3.csv"
    //   },
    //   {
    //     "attachmentInfoId": "bb77fbb3-e83d-43a1-843e-ac50cc2d3b1b",
    //     "attachmentName": "img_3.png",
    //     "attachmentUrl": "spaConversion/image/img_3.png"
    //   }]
    // ]
  }

  const spaUploadFn = ({ list, index, fileIndex, isRemove }) => {
    console.log("🚀 ~ imgUploadFn ~ list:", list)
    const listNames = 'product';
    const productData = form?.getFieldsValue()?.[listNames];
    const productItemData = form?.getFieldsValue()?.[listNames]?.[index];
    const files = productItemData?.attachmentUrl?.fieldValue || []
    if (list?.length > 0) {
      const newList = list.map(d => {
        return {
          imageAttachment: d[2],
          spaAttachment: d[0],
          csvAttachment: d[1]
        }
      })

      productItemData.attachmentUrl = {
        ...productItemData.attachmentUrl,
        fieldName: 'attachmentUrl',
        fieldValue: files.concat(newList)
      }
    } else if (isRemove) {
      const imageAttachment = productItemData?.attachmentUrl?.fieldValue[fileIndex]?.imageAttachment
      const csvAttachment = productItemData?.attachmentUrl?.fieldValue[fileIndex]?.csvAttachment
      const spaAttachment = productItemData?.attachmentUrl?.fieldValue[fileIndex]?.spaAttachment
      if (productItemData?.attachmentUrl?.fieldDeleteValue) {
        productItemData.attachmentUrl.fieldDeleteValue.push(imageAttachment, csvAttachment, spaAttachment)

      } else {
        productItemData.attachmentUrl.fieldDeleteValue = [imageAttachment, csvAttachment, spaAttachment]

      }
      productItemData.attachmentUrl.fieldValue.splice(fileIndex, 1)
    }

    productData[index] = {
      ...productItemData,
    };
    form.setFieldsValue({
      [listNames]: productItemData,
    });

  }

  //匹配和图片同名并且 当前图片没有txt文件
  const txtFilterFn = ({ list, index }) => {
    const listNames = 'product';
    const productItemData = form?.getFieldsValue()?.[listNames]?.[index];
    const files = productItemData?.attachmentUrl?.fieldValue || []

    const uploadFiles = []
    list.forEach(d => {
      const { fileName, extension } = getFileName(d.name)
      const isImageExist = (files || []).some(item => item.imageAttachment?.fileName === fileName && !item.txtAttachment?.fileName)
      if (extension === 'txt' && isImageExist) {
        uploadFiles.push(d)
      }
    })

    return uploadFiles
  }

  //拿到上传后的txt文件
  const txtUploadFn = ({ index, fileIndex, list, isRemove }) => {
    const listNames = 'product';
    const productData = form?.getFieldsValue()?.[listNames];
    const productItemData = form?.getFieldsValue()?.[listNames]?.[index];
    const files = productItemData?.attachmentUrl?.fieldValue || []

    if (list?.length > 0) {
      list.forEach(d => {
        const { fileName, extension } = getFileName(d.attachmentName)
        for (let item of (files || [])) {
          console.log("item.imageAttachment?.fileName === fileName", item.imageAttachment?.fileName, fileName)
          if (item.imageAttachment?.fileName === fileName) {
            item.txtAttachment = {
              ...d,
              extension,
              fileName,
            }
            break;
          }
        }
      })
    } else if (isRemove) {
      if (productItemData?.attachmentUrl?.fieldDeleteValue) {
        productItemData.attachmentUrl.fieldDeleteValue.push(productItemData.attachmentUrl.fieldValue[fileIndex].txtAttachment)
      } else {
        productItemData.attachmentUrl.fieldDeleteValue = [productItemData.attachmentUrl.fieldValue[fileIndex].txtAttachment]
      }
      productItemData.attachmentUrl.fieldValue[fileIndex].txtAttachment = undefined
    }

    productData[index] = {
      ...productItemData,
    };
    form.setFieldsValue({
      [listNames]: productItemData,
    });
  }

  //上传去重已经上传过的文件
  const imgFilterFn = ({ list, index }) => {
    const listNames = 'product';
    const productItemData = form?.getFieldsValue()?.[listNames]?.[index];
    const files = productItemData?.attachmentUrl?.fieldValue || []

    const uploadFiles = []
    list.forEach(d => {
      const { fileName, extension } = getFileName(d.name)
      if (/^image\//i.test(d.type) && !(files || []).some(item => item.imageAttachment?.fileName === fileName)) {
        uploadFiles.push(d)
      }
    })
    return uploadFiles
  }

  //拿到上传后的图片
  const imgUploadFn = ({ index, fileIndex, list, isRemove }) => {
    console.log("🚀 ~ imgUploadFn ~ list:", list)
    const listNames = 'product';
    const productData = form?.getFieldsValue()?.[listNames];
    const productItemData = form?.getFieldsValue()?.[listNames]?.[index];
    const files = productItemData?.attachmentUrl?.fieldValue || []
    if (list?.length > 0) {
      const newList = list.map(d => {
        const { fileName, extension } = getFileName(d.attachmentName)
        return {
          imageAttachment: {
            ...d,
            extension,
            fileName,
          }
        }
      })
      productItemData.attachmentUrl = {
        ...productItemData.attachmentUrl,
        fieldName: 'attachmentUrl',
        fieldValue: files.concat(newList)
      }
    } else if (isRemove) {
      const imageAttachment = productItemData?.attachmentUrl?.fieldValue[fileIndex]?.imageAttachment
      const txtAttachment = productItemData?.attachmentUrl?.fieldValue[fileIndex]?.txtAttachment
      if (productItemData?.attachmentUrl?.fieldDeleteValue) {
        productItemData.attachmentUrl.fieldDeleteValue.push(imageAttachment)

      } else {
        productItemData.attachmentUrl.fieldDeleteValue = [imageAttachment]

      }
      if (txtAttachment) {
        productItemData.attachmentUrl.fieldDeleteValue.push(txtAttachment)
      }
      productItemData.attachmentUrl.fieldValue.splice(fileIndex, 1)
    }

    productData[index] = {
      ...productItemData,
    };
    form.setFieldsValue({
      [listNames]: productItemData,
    });
  }
  const uploadRender = ({ index, fileIndex, imgFileList = [], fileList = [], isFiles = false }) => {
    const isDisabledTag = imgFileList.length > 0 || fileList.length > 0 ? false : true;
    let uploadClassName = ''
    if (!isSEM && imgFileList.length === 0) {
      if (isFiles) {
        uploadClassName = 'uploadHidden'
      } else {
        uploadClassName = 'uploadRemove'
      }
    }
    return (
      <div className='searchUpload' key={fileIndex || 9999}>
        <Form.Item
          noStyle={true}
        >
          <UploadImg
            uploadUpdateFn={(list, isRemove) => imgUploadFn({ list, index, fileIndex, isRemove })}
            uploadName="search"
            uploadModule="product"
            isHideText={!isSEM}
            disabled={!(initialValues?.project?.requestStatus?.fieldValue === APPROVED && editMode === RES_MODE.TESTEREDIT)}
            linkFn={linkFn}
            fileListData={imgFileList}
            maxCount={999}
            className={uploadClassName}
            beforeFilterFn={(list) => imgFilterFn({ list, index })} />
        </Form.Item>
        <Form.Item
          noStyle={true}>
          {
            isSEM ? (
              <UploadFile
                uploadUpdateFn={(list, isRemove) => txtUploadFn({ list, index, fileIndex, isRemove })}
                uploadName="search"
                uploadModule="product"
                btnText={isSEM ? t('search.uploadText') : t('search.uploadSpa')}
                acceptType={isSEM ? ACCEPT_TYPE.TXT : ACCEPT_TYPE.SPA}
                disabled={!(initialValues?.project?.requestStatus?.fieldValue === APPROVED && editMode === RES_MODE.TESTEREDIT)}
                fileListData={fileList}
                maxCount={999}
                isHide={fileIndex !== undefined}
                beforeFilterFn={(list) => txtFilterFn({ list, index })} />
            ) : (
              <UploadFile
                uploadUpdateFn={(list, isRemove) => spaUploadFn({ list, index, fileIndex, isRemove })}
                uploadName="search"
                uploadModule="product"
                btnText={t('search.uploadSpa')}
                acceptType={ACCEPT_TYPE.SPA}
                disabled={!(initialValues?.project?.requestStatus?.fieldValue === APPROVED && editMode === RES_MODE.TESTEREDIT)}
                fileListData={fileList}
                maxCount={999}
                uploadApiFn={uploadSpaApi} />
            )
          }

        </Form.Item>
        {
          !isDisabledTag && (
            <Form.Item
              noStyle={true}
              name={[index, 'attachmentUrl', 'fieldValue', fileIndex, 'tagValue']}>
              <Select
                className='select'
                mode="tags"
                placeholder={t('search.addTags')}
                allowClear
                disabled={isDisabledTag || !(initialValues?.project?.requestStatus?.fieldValue === APPROVED && editMode === RES_MODE.TESTEREDIT)}
                options={compTagList} />
            </Form.Item>
          )
        }

      </div>
    )
  }
  const productExtraContentrRender = (index) => {
    const listNames = 'product';
    const productItemData = form?.getFieldsValue()?.[listNames]?.[index];
    const isFiles = productItemData?.attachmentUrl?.fieldValue?.length > 0

    return (
      <Col span={24} key={index}>
        <Flex gap={24} wrap='wrap'>
          {
            (productItemData?.attachmentUrl?.fieldValue || []).map((d, fileIndex) => {

              const imgFileList = [d?.imageAttachment] // resquestDetialAttachmentFormat(d?.imageAttachment?.attachmentUrl);
              const fileList = isSEM ? resquestDetialAttachmentFormat(d?.txtAttachment?.attachmentName) : resquestDetialAttachmentFormat(d?.spaAttachment?.attachmentName);

              return uploadRender({
                index,
                fileIndex,
                imgFileList,
                fileList,
              })
            })
          }
          {initialValues?.project?.requestStatus?.fieldValue === APPROVED && editMode === RES_MODE.TESTEREDIT && uploadRender({ index, isFiles })}


        </Flex>
      </Col>
    )
  };

  useEffect(() => {
    // 获取模板数据
    let initData = {};
    if (tplId && editMode === RES_MODE.NEW) {
      apiSysTemplateInitiate({ templateName: tTm, buType: tBu, moduleName: tMd }).then((res) => {
        if (res?.data?.code === 200) {
          initData = {
            project: res?.data?.data?.Project,
            product: [
              {
                ...res?.data?.data?.Product
              }
            ]
          };
          setInitialValues(initData);
        }
      })
    } else if (searchRequestId && (editMode === RES_MODE.APPROVAL || editMode === RES_MODE.VIEW || editMode === RES_MODE.EDIT || editMode === RES_MODE.TESTEREDIT)) {
      apiSearchRequestView({
        searchRequestId: searchRequestId,
        userId: getUserName(),
      }).then((res) => {
        if (res?.data?.code === 200) {
          const newProject = formatRequestItemData(res?.data?.data?.item?.project);
          const newProduct = res?.data?.data?.item?.product?.map((prdItem) => {
            prdItem?.attachmentUrl?.fieldValue?.map(d => {
              const { fileName, extension } = getFileName(d?.imageAttachment?.attachmentName)
              const { fileName: txtFileName, extension: txtExtension } = getFileName(d?.txtAttachment?.attachmentName)
              d.imageAttachment = {
                ...d?.imageAttachment,
                fileName,
                extension
              }
              if (d?.txtAttachment && txtFileName) {
                d.txtAttachment = {
                  ...d.txtAttachment,
                  fileName: txtFileName,
                  extension: txtExtension
                }
              }
            })
            return formatRequestItemData(prdItem)
          });
          if (res?.data?.data?.item?.requestStatus === APPROVED) {
            apiMSDTagSelectAsync(newProject);
          }
          console.log("🚀 ~ newProduct ~ newProduct:", newProduct)
          console.log("🚀 ~ newProduct ~ newProduct:", newProduct)
          // console.log(newProject);
          // console.log('____________________');
          // console.log(newProduct);
          // console.log('--------------------');
          initData = {
            project: newProject,
            product: newProduct,
          };
          setRequestStatus(res?.data?.data?.item?.requestStatus)
          setInitialValues(initData);
        }
      })
    };
  }, []);

  const linkFn = (data) => {
    console.log("🚀 ~ linkFn ~ data:", data)
    setChooseImageModalVisable(true)
    setLinkImage(data)
  }

  const onConfirmModal = (data) => {
    console.log("🚀 ~ onConfirmModal ~ data:", data)
    if (isSEM) {
      navigate('/search/sem', {
        state: {
          chooseImageDefault: {
            ...data,
            imageAttachment: [{
              attachmentUrl: linkImage.attachmentUrl,
              name: linkImage.attachmentName,
            }]
          }
        }
      });
    }

  }

  return (
    <>
      {
        initialValues &&
        <>
          <div className='page-title-wrap'>
            <Flex align='center' justify='space-between'>
              <Title className='fontStyleH2' level={2} >{editMode === RES_MODE.NEW ? t(`common.newRequest`) : t(`common.requestDetail`)}</Title>
              <div>
                <RequestApprovalBtn
                  approveRequestSituationId={approveRequestSituationId}
                  form={form}
                  moduleConfig={REQUEST_PAGE.Search}
                  initialValues={initialValues}
                  editMode={editMode} />
                {
                  (
                    //可填写测试数据 save
                    ((isCampAdmin || isBuPRPD || isBuAdmin || isBuTester) && initialValues?.project?.requestStatus?.fieldValue === APPROVED) ||
                    //可重新编辑 save
                    ((isCampAdmin || isBuPRPD || isBuAdmin) && (initialValues?.project?.requestStatus?.fieldValue === DRAFT || initialValues?.project?.requestStatus?.fieldValue === REJECTED || initialValues?.project?.requestStatus?.fieldValue === APPROVED || editMode === RES_MODE.NEW))
                  ) && editMode !== RES_MODE.VIEW &&
                  <Button onClick={() => { saveClickHandle('save') }} style={{ marginRight: '10px' }}>{t('common.save')}</Button>
                }
                {

                  //可重新编辑 submit
                  (isCampAdmin || isBuPRPD || isBuAdmin) && (initialValues?.project?.requestStatus?.fieldValue === DRAFT || initialValues?.project?.requestStatus?.fieldValue === REJECTED || editMode === RES_MODE.NEW) && editMode !== RES_MODE.VIEW &&
                  <Button type='primary' onClick={() => { saveClickHandle('submit') }}>{t('common.submit')}</Button>
                }
              </div>
            </Flex>
          </div>
          <div className='page-content-wrap'>
            <Form form={form}
              initialValues={initialValues}
              disabled={editMode === RES_MODE.VIEW || editMode === RES_MODE.TESTEREDIT || editMode === RES_MODE.APPROVAL}
            >
              {/* Project */}
              <RequestFormProjectTpl
                uploadParams={{ type: 'synTouch', name: 'project' }}
                tplData={queryParams}
                listNames='project'
                form={form}
                initialValues={initialValues}
                editMode={editMode}
                moduleConfig={REQUEST_PAGE['Search']}
              />
              {/* Product */}
              <RequestFormProductTpl
                uploadParams={{ type: 'synTouch', name: 'product' }}
                listNames='product'
                form={form}
                initialValues={initialValues}
                productExtraContentrRender={productExtraContentrRender}
                editMode={editMode}
                moduleConfig={REQUEST_PAGE['Search']}
              />
            </Form>
          </div>

          <ChooseImageModal
            chooseImageModalVisable={chooseImageModalVisable}
            setChooseImageModalVisable={setChooseImageModalVisable}
            isUploadImage={false}
            methodList={methodList}
            onConfirm={onConfirmModal} />
        </>
      }
    </>
  )
};

export default SynTouchRequestDetails;
